﻿using stirling_chillers.Services;
using stirling_chillers.Views;

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace stirling_chillers.ViewModels
{
    /// <summary>
    /// 登录视图模型
    /// </summary>
    public class LoginViewModel:BindableBase
    {
        #region 属性绑定
        /// <summary>
        /// 用户名
        /// </summary>
        private string _username;

        public string Username
        {
            get { return _username; }
            set 
            {
                //SetProperty(ref _username, value); 
                _username = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 密码
        /// </summary>
        private string _password;

        public string Password
        {
            get { return _password; }
            set 
            { 
                SetProperty(ref _password, value);
            }
        }

        #endregion

        /// <summary>
        /// 定义命令
        /// </summary>
        public DelegateCommand LoginCommand { get; }

        private readonly IAuthService _authService;
        private readonly LoginView _loginView;
        private readonly ErrorsContainer<string> _errorsContainer;//用于解析主窗口
        private readonly IContainerProvider _containerProvider;
        private readonly IRegionManager _regionManager;


        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginViewModel(IAuthService authService,LoginView loginView,IContainerProvider containerProvider, IRegionManager regionManager)
        {

             _authService = authService;
             _loginView = loginView;
            _containerProvider = containerProvider;
            _regionManager = regionManager;

             LoginCommand = new DelegateCommand(ExecuteLoginAsync);


        }

        /// <summary>
        /// 执行登录
        /// </summary>
        private async void ExecuteLoginAsync()
        {

      
                var result = await _authService.LoginAsync(Username, Password);

                if (result.Success)
                {

                    // 登录成功，先关闭登录窗口
                    _loginView.Close();
                    //创建主窗口
                    var mainWindow = _containerProvider.Resolve<MainWindow>();
                        mainWindow.Show();
                   

                    //导航到主界面
                    var regionManager = _containerProvider.Resolve<IRegionManager>();
                    regionManager.RequestNavigate("MainRegion", "MainView");
                }
        }
    }
}
